import axios from 'axios'
import { getCookie } from "../js/common/util"
import  baseURL from '@/js/common/baseURL.js'
import router from '@/router/index'
import 'url-search-params-polyfill'
import { Loading, Message } from 'element-ui'

let loadingInstance = null;

const instance = axios.create({
  baseURL: baseURL,
  timeout: 1000000,
  withCredentials:true,
});

instance.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


instance.interceptors.request.use(
  config => {
    var token = ''
    if(typeof getCookie('token') === 'undefined'){
      router.push({
        path: '/login',
        query:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
      });
    }else {
      token = getCookie('token');
    }//注意使用的时候需要引入cookie方法，推荐js-cookie
    if(!config.notStringify) {
      config.data = JSON.stringify(config.data);
    }
    if(token != ''){
      config.headers.Authorization = `${token}`;
    }
    
    showLoading();
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
//http response 封装后台返回拦截器
instance.interceptors.response.use(
  response => {
    hideLoading();
    console.log('response-----------',response)
    //当返回信息为未登录或者登录失效的时候重定向为登录页面
    if(response.data.data != null && response.data.data.code == "9999"){
      router.push({ path: '/login' })
    }else if(response.data.data != null && response.data.data.code == "0000"){
      router.push({
        path: '/401',
        // query:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
      });
    }if(response.data.data != null && response.data.data.code == "1111"){
      router.push({
        path: '/401',
        // query:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
      });
    }else {
      if(response.data.success === true || response.data.success == null) {
        return response;
      } else {
        if(!(response && response.config && response.config.hideError)) {
          Message({
            message: response.data.msg || "系统错误，请联系管理员:)",
            type: "error"
          });
        }

        return Promise.reject(response.data.msg || "系统错误，请联系管理员:)");
      }
    }

  },
  error => {
    hideLoading();
    if(!(error && error.response && error.response.config && error.response.config.hideError)) {
      Message({
        message: "系统错误，请联系管理员",
        type: "error"
      });
    }
    return Promise.reject(error)
  }
)

let count = 0;
function showLoading() {
//  loadingInstance.show();
  if(count === 0) {
    loadingInstance = Loading.service({
      lock: true,
      // text: 'Loading',
      // spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.5)'
    });
  }
  
  count++;
}

function hideLoading() {
  count--;
  if(count === 0) {
    loadingInstance.close();
  }
}

export default instance;

